﻿using Microsoft.Win32;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WinForms = System.Windows.Forms;
namespace txt2xls
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
   
    public partial class MainWindow : Window
    {
        private string dirPath;
        private string fileName;
        private StreamReader reader;
        private List<string> textModel;
        private String tempStr;
        private int stat;
        private BufferedStream bufStream;
        public MainWindow()
        {
            InitializeComponent();
            textModel = new List<string>();
            stat = 0;
        }

        private void ButtOpen_Click(object sender, RoutedEventArgs e)
        {
            switch (stat)
            {
                case 0:
                    {
                        if (getFile(0)) makeModel(fileName, 100); break;

                    }
                case 1: if (getFile(1)) makeExel(); break;



            }


        }

        private void makeExel()
        {

            int maxCol;
            int atRow = 1;
            int atcol = 1;
            //获得文件列表
            List<string> fileList = new List<string>();
            DirectoryInfo dir = new DirectoryInfo(dirPath);
            if (dir.Exists)
            {
               // foreach (DirectoryInfo dinfo in dir.GetDirectories())
               // {
                    foreach (FileInfo info in dir.GetFiles("*.txt"))
                   // {
                        fileList.Add(info.FullName.ToString());
                   // }
             // }
            }

            //获得要取项

            if (textModel.Count > 0) textModel.Clear();
            foreach (CheckBox c in wrapPan.Children)
            {
                if (c.IsChecked == true&&!c.Content.Equals("全选")) textModel.Add(c.Content.ToString());
            }
           
            
            //Epplus开始
            maxCol = textModel.Count;
            if (maxCol > 0)
            {
                var str = "";
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                ExcelPackage excelP = new ExcelPackage(new FileInfo(dirPath +"\\"+DateTime.Now.ToString("yymmddhhss")+".xlsx"));
                ExcelWorksheet worksheet = excelP.Workbook.Worksheets.Add("sheet1");
                int j = 1;
               //把项目名做第一行
                foreach (String st in textModel)
                {
                    worksheet.Cells[1, j].Value = st;
                    j++;
                }
                atRow = atRow+ 1;
                //开始读文件循环
                textBl.Text = "正在加工文件请稍等 ...";
                for (int i = 0; i < fileList.Count; i++)
                {
                   
                    reader = new StreamReader(fileList[i], Encoding.GetEncoding("gb2312"));
                   // tempStr = reader.ReadLine();
                    while ((tempStr = reader.ReadLine()) != null)
                    {
                       // if (str.Contains("%")) continue;
                        str = tempStr.Trim();
                        var t3 = "";
                        if (str.Contains("="))
                        {
                            t3 = str.Substring(0, str.IndexOf("="));
                            if (t3.Equals(textModel[atcol - 1]))
                            {
                                var t1 = str.IndexOf("=");

                                var t2 = textModel.IndexOf(t3);

                                worksheet.Cells[atRow, textModel.IndexOf(str.Substring(0, t1)) + 1].Value = str.Substring(t1 + 1, str.Length - t1 - 1);

                                if (atcol < maxCol) atcol++; else { atcol = 1; atRow++; }

                            }
                        }
                        
                    }
                    reader.Close();
                }
                //输出exl
               
                excelP.Save();
                textBl.Text = "文件保存完成";
            }
        }
        private bool getFile(int stat)
        {
            if (TextOpen.Text != null && TextOpen.Text.Length > 0)//非空检查
            {
                if (System.IO.File.Exists(TextOpen.Text))
                {
                    fileName = TextOpen.Text;
                    dirPath = System.IO.Path.GetDirectoryName(fileName);
                    return true;
                }
                else { TextOpen.Text = ""; }


            }
            if (TextOpen.Text != null && TextOpen.Text.Length == 0)//如果空打开文件选择对话框
            {
                
                
                switch (stat)
                {
                    case 0:
                        OpenFileDialog openFileDialog = new OpenFileDialog();
                        openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
                        if (openFileDialog.ShowDialog() == true )
                        {
                            fileName = openFileDialog.FileName;


                        }
                        else return false;
                        if (fileName != null && fileName.Length > 0)
                        {
                            dirPath = System.IO.Path.GetDirectoryName(fileName);
                            TextOpen.Text = "";

                            return true;
                        }
                        break;
                    case 1:
                        WinForms.FolderBrowserDialog folderDialog = new WinForms.FolderBrowserDialog();
                        if (folderDialog.ShowDialog() == WinForms.DialogResult.OK)
                        {
                            dirPath = folderDialog.SelectedPath;


                        }
                        else return false;
                        if (dirPath != null && dirPath.Length > 0)
                        {
                            
                            TextOpen.Text = dirPath;

                            return true;
                        }
                        break;
                }
                 

                
                
                
               

            }
            return false;
        }

        //读取txt文件，取出可取项目以“=”为标志
        private void makeModel(string fileName,int count)
        {
            textBl.Text = "开始读取文件，分析模型...";
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            reader = new StreamReader(fileName,Encoding.GetEncoding("gb2312"));

            var i=0;
           
            var str = "";
            //  var strIndex = 0;
            if (textModel.Count > 0) textModel.Clear();
            
            
            while((tempStr= reader.ReadLine()) != null) 
            {

               listBox.Items.Add(tempStr);
                str=tempStr.Trim();
                if (str.Contains("%%")) continue;
                if (str.Contains("=") )
                {
                    str = str.Substring(0, str.IndexOf("="));
                    if (textModel.Find(xxx => xxx.Equals(str)) == null)
                    {

                        textModel.Add(str);
                       // listBox.Items.Add(str);
                    }
                }





                if (i < count) { i++; } else break;



            }
            
            reader.Close();
            makeChkBox(textModel);
            textBl.Text = "请确定要提取的项目";
        }
        //根据textModel生成CheckBox带全选功能
        private void makeChkBox(List<String> str)
        {
            var i = str.Count;
           
            if (i > 0)
            {
               // Thickness margin = new Thickness(10);
                CheckBox cbAll = new CheckBox { Content = "全选",Width=130  };
                cbAll.Click +=new RoutedEventHandler(cbAll_click);
                wrapPan.Children.Add(cbAll) ;
                
                for (var j=0; j<i; j++)
                {
                    wrapPan.Children.Add(new CheckBox { Content = str[j], Name = "cb" + j ,Width=130}) ;
                }
            }
            textBl.Text = "选择文件目录";
            ButtOpen.Content = "开始";
            
            stat = 1;
        }

        //全选CheckBox
        private void cbAll_click(object sender, RoutedEventArgs e)
        {
            CheckBox send = sender as CheckBox;


            if (send.IsChecked==true)
            {
                foreach(CheckBox c in wrapPan.Children)
                {
                    c.IsChecked = true;
                }
                
               
            }
            else
            {
                foreach (CheckBox c in wrapPan.Children)
                {
                    c.IsChecked = false;
                }

                

            }
        }
    }








}
